<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Category;
use App\Model\Content;

class CateController extends Controller
{
  // 根据id获取分类信息
  public function getCateById($id)
  {
    $data = Category::where('id', $id)->first();
    return response()->json(['status' => 200, 'body' => $data]);
  }

  // 添加栏目
  public function addCate(Request $request)
  {
    // 获取请求参数
    $data = $request->all();
    // 通过分类名称获取分类信息
    $cate = Category::where('name', $data['name'])->first();
    if ($cate) {
      return response()->json(['status' => 400, 'msg' => '该分类已存在']);
    }
    $res = Category::create($data);
    if (!$res) return response()->json(['status' => 400, 'msg' => '添加栏目失败']);
    return response()->json(['status' => 200, 'msg' => '添加栏目成功']);
  }

  // 删除栏目
  public function removeCateById($id)
  {
    // 通过栏目id获取内容
    $data = Content::where('cid', $id)->get();
    // 判断栏目下是否存在内容
    if (count($data) > 0) return response()->json(['status' => 400, 'msg' => '当前栏目下存在内容']);
    $res = Category::where('id', $id)->delete();
    if (!$res) return response()->json(['status' => 400, 'msg' => '删除栏目失败']);
    return response()->json(['status' => 200, 'msg' => '删除栏目成功']);
  }

  // 修改栏目
  public function updateCateById(Request $request, $id)
  {
    $data = $request->all();
    // 根据分类名称获取分类信息
    $cate = Category::where('name', $data['name'])->first();
    if ($cate) {
      return response()->json(['status' => 400, 'msg' => '该分类已存在']);
    }
    // 根据id修改栏目信息
    $res = Category::where('id', $id)->update($data);
    if (!$res) return response()->json(['status' => 400, 'msg' => '修改栏目失败']);
    return response()->json(['status' => 200, 'msg' => '修改栏目成功']);
  }

  // 根据id修改栏目排序
  public function updateCateSort(Request $request, $id)
  {
    $sort = $request->get('sort');
    $res = Category::where('id', $id)->update(['sort' => $sort]);
    if (!$res) return response()->json(['status' => 400, 'msg' => '修改栏目失败']);
    return response()->json(['status' => 200, 'msg' => '修改栏目成功']);
  }
}
